import datetime
import json

import jqdatasdk
from django.core.management.base import BaseCommand
from stocksys import models as stocksys_models


class Command(BaseCommand):
    help = 'create_stock_data_from_jqdata'

    def handle(self, *args, **options):

        self.stdout.write(self.style.SUCCESS('清空股票数据'))
        stocksys_models.Stock.objects.all().delete()
        self.stdout.write(self.style.SUCCESS('验证远程数据密钥'))
        auth_key = None
        with open("data/auth_key.key") as key:
            auth_key = key.read().split(",")
            jqdatasdk.auth(auth_key[0], auth_key[1])
            print(auth_key)
        # self.create_stock_to_industry('000001.XSHE')
        # exit()
        self.stdout.write(self.style.SUCCESS('请求远程数据'))
        data = jqdatasdk.get_all_securities(['stock'])
        # data.to_csv("../data/all_exchange_code.csv")
        self.stdout.write(self.style.SUCCESS('初始化数据'))
        data['code'] = data.index
        data.index = [x for x in range(len(data))]
        data['stock_code'] = data['code'].map(lambda x: x.split('.')[0])
        data['jqdata_abbreviated'] = data['code'].map(lambda x: x.split('.')[1])

        data['abbreviated_name'] = data['name']
        data = data.drop('name', axis=1)
        data['stock_name'] = data['display_name']
        data = data.drop('display_name', axis=1)
        data['last_update_time'] = datetime.datetime.now().strftime("%Y-%m-%d")
        data = data[
            ['stock_name', 'abbreviated_name', 'stock_code', 'last_update_time',
             'start_date', 'end_date', 'type', 'jqdata_abbreviated']]

        self.stdout.write(self.style.SUCCESS('载入股票代码数据'))
        for index in range(len(data)):
            row = data.loc[index].to_dict()
            jqdata_abbreviated = row['jqdata_abbreviated']
            print(jqdata_abbreviated)
            # 股票交易所地址
            exchange_address = stocksys_models.ExchangeAddress.objects.get(
                stock_jqdata_name=jqdata_abbreviated)

            stocksys_models.Stock.objects.create(
                name=row['stock_name'],
                code=row['stock_code'],
                last_update_time=row['last_update_time'],
                start_date=row['start_date'].to_pydatetime(),
                end_date=row['end_date'].to_pydatetime(),
                type=row['type'],
                exchange_address=exchange_address,
                abbreviated_name=row['abbreviated_name']
            )
            stock = stocksys_models.Stock.objects.get(code=row['stock_code'], abbreviated_name=row['abbreviated_name'])
            jqdata_stock_code = "%s.%s" % (stock.code, jqdata_abbreviated)
            self.create_stock_to_industry(jqdata_stock_code, stock)
        self.stdout.write(self.style.SUCCESS('结束载入'))

    def create_stock_to_industry(self, jqdata_stock_code, stock):
        print(jqdata_stock_code)
        industry = jqdatasdk.get_industry(jqdata_stock_code, date=datetime.datetime.now().strftime("%Y-%m-%d"))
        if industry != None:
            for industry_level, industry_info in industry[jqdata_stock_code].items():
                industry_code = industry_info['industry_code']
                industry_name = industry_info['industry_name']
                try:
                    # 获取股票所属行业
                    industry_model = stocksys_models.Industry.objects.get(code=str(industry_code))
                    stocksys_models.StockIndustry.objects.create(stock=stock, industry=industry_model)
                except Exception as e:
                    self.stdout.write(self.style.ERROR(str([industry_code, industry_name])))
                    self.stdout.write(self.style.ERROR(jqdata_stock_code))
                    self.stdout.write(self.style.ERROR(e))
                    exit()
